/***********************************************
 This file is part of redia-library-app-ios.
 
 Copyright (c) 2012, 2013 Redia A/S
 
 Redia-library-app-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-library-app-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-library-app-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */


#import "InfoGalleriPlistPackageFetcher.h"
#import "defines.h"

@implementation InfoGalleriPlistPackageFetcher

@synthesize customerId;
@synthesize galleryId;

SINGLETON_IMPL_GCD(InfoGalleriPlistPackageFetcher)

- (id)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

-(BOOL)fetchPlistCacheForCustomer:(NSString*)customer withGallery:(NSString*)gallery delegate:(id<PackageFetchComplete,ProgressDisplayDelegate>)_delegate
{
    delegate =  _delegate;

    self.customerId=customer;
    self.galleryId=gallery;
    
    url = [NSURL URLWithString:[NSString stringWithFormat:REDIA_APP_PLIST_PACKAGE_FETCH_URL "%@/%@/InfoGalleriElementCache.plist",customer,gallery]];
    DLog(@"url: %@",url);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString* elementCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"InfoGalleriElementCache-temp.plist"];
	//NSFileManager* filemgr = [NSFileManager defaultManager];
    outputFile = [[NSOutputStream alloc] initToFileAtPath:elementCachePath append:NO];
    [outputFile setDelegate:self];
    [outputFile open];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    if (![request valueForHTTPHeaderField: @"Accept-Encoding"]) {
        [request addValue:@"gzip" forHTTPHeaderField: @"Accept-Encoding"];
    } else {
        [request setValue:@"gzip" forHTTPHeaderField: @"Accept-Encoding"];
    }
    
    DLog(@"get headers: %@",[request allHTTPHeaderFields]);
    myConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    
    if (myConnection==nil) {
        return FALSE;
    }
    return TRUE;

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"InfoGalleriPlistPackageFetcher load image error: %@",error);
    NSLog(@"error url: %@",url);
	[delegate packageFetchError:error];
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
	if ([response respondsToSelector:@selector(statusCode)])
	{
        NSHTTPURLResponse* http_res = (NSHTTPURLResponse *)response;
		int statusCode = [http_res statusCode];
		if (statusCode >= 400)
		{
			[conn cancel];  // stop connecting; no more delegate messages
			NSDictionary *errorInfo
			= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
												  NSLocalizedString(@"Server returned status code %d",@""),
												  statusCode]
										  forKey:NSLocalizedDescriptionKey];
			NSError *statusError
			= [NSError errorWithDomain:NSURLErrorDomain
								  code:statusCode
							  userInfo:errorInfo];
			[self connection:conn didFailWithError:statusError];
		}
        //DLog(@"headers: %@",[http_res allHeaderFields]);
	} else {
		receivedLength=0;
	}
    
    totalLength = [response expectedContentLength];
    
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [outputFile write:[data bytes] maxLength:[data length]];
    receivedLength += [data length];
    float completed = ((double) receivedLength)/((double)totalLength);
    //DLog(@"completed: %lf", completed);
    
    if (delegate!=nil && [delegate respondsToSelector:@selector(progress:)]) {
        [delegate progress:completed];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    DLog(@"InfoGalleriPlistPackageFetcher load received %lld bytes of data", receivedLength);
	
    [outputFile close];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString* elementCachePath_temp = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"InfoGalleriElementCache-temp.plist"];
	NSString* elementCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"InfoGalleriElementCache.plist"];
    
    NSError* error;
    BOOL result1 = [[NSFileManager defaultManager] removeItemAtPath:elementCachePath error:&error];
    if (!result1) {
        DLog(@"remove error: %@",error);
    } 
    BOOL result2 = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:elementCachePath_temp] toURL:[NSURL fileURLWithPath:elementCachePath] error:&error];
    if (!result2) {
        DLog(@"move error: %@",error);
        [delegate packageFetchError:error];
    } else {
        [delegate packageFetchComplete:elementCachePath];
    }
    
    
}



- (void)cancelRequest
{
	if (myConnection!=nil) {
		delegate = nil;
		[myConnection cancel];
	}
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    DLog(@"event code: %d",eventCode);
}


@end
